﻿using System;
using System.Collections.Generic;

namespace Bibylon.BehafX.StateMachine.concept
{

    internal abstract class selector : composite
    {
        /// <summary>
        /// c'tor... nothing special
        /// </summary>
        public selector(string name, int nid, node parent)
            : base(name, nid, parent)
        {
            //
        }

        /// <summary>
        /// @Copydoc - node::Category
        /// </summary>
        public override string Category
        {
            get { return "Selector"; }
        }

        /// <summary>
        /// @Copydoc - Block::execute; 
        /// </summary>
        internal override int execute(object agent, object any)
        {
            if (OngoingChild == -1)
                OngoingChild = 0; // rewind running index.

            Status result = Status.Failed;

            // foreach
            for (int n = OngoingChild; n < Children.Count; n++)
            {
                node child = Children[n];

                // No we'd got the child do all the job of itself.
                // child.execute(agent, any);
                child.evaluate(agent, any);
                result = child.QueryStatus;

                if (child.QueryStatus == Status.Running)
                {
                    OngoingChild = n;
                    break;
                }
                else
                {
                    OngoingChild = -1; // try next ?
                }

                if (child.QueryStatus == Status.Successful) // just opposite to squence
                {
                    break; // 
                }
            }

            if (result != Status.Running) // we can make the conclusion
            {
                OngoingChild = -1;
            }

            QueryStatus = result; return (int)result;
        }
    }
}
